package petertel.pbx.conf.logger;

import java.util.Iterator;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import petertel.pbx.utils.ConfigItem;
import petertel.pbx.utils.ConfigParser;
import petertel.pbx.utils.ParserUtils;

@Controller
@Scope("session")
@RequestMapping("/loggerConf")
public class LoggerConf {

	private ConfigItem config;

	private String doShow() {
		return "loggerConf_show";
	}

	private boolean toggle;

	public boolean getToggle() {
		return toggle = !toggle;
	}

	@RequestMapping(value = "/reset")
	public String reset() {
		config = ConfigParser.parse("/etc/asterisk/logger.conf");
		return doShow();
	}

	@RequestMapping(value = "/apply")
	public String apply() {
		return reset();
	}

	@RequestMapping(value = "/remove")
	public String remove(int index) {
		return doShow();
	}

	@RequestMapping(value = "/checkLoglevel")
	public String checkLoglevel(int index, Loglevel.Type loglevel,
			boolean checked) {
		return doShow();
	}

	@RequestMapping(value = "/insert")
	public String insert(int index, String filename) {
		return doShow();
	}

	public String getApplyButtonClass() {
		return "button-blue";
	}

	public Iterator<Logfile> getLogfiles() {
		ConfigItem logfilesSection = getLogfilesSection();
		final Iterator<ConfigItem> iter = logfilesSection.getChildren();
		return new Iterator<Logfile>() {

			public boolean hasNext() {
				return iter.hasNext();
			}

			public Logfile next() {
				return new Logfile(iter.next());
			}

			public void remove() {
				;
			}

		};
	}

	private ConfigItem getLogfilesSection() {
		Iterator<ConfigItem> iter = config.getChildren();
		while (iter.hasNext()) {
			ConfigItem child = iter.next();
			String name = ParserUtils.getSectionName(child.getLine());
			if (name.equals("logfiles")) {
				return child;
			}
		}
		return null;
	}

	private boolean isDirty() {
		return false;
	}

}
